package mobi.springtour.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class WriteImg {
	static LinkedHashMap<String, SoftReference<Bitmap>> imageCache = new LinkedHashMap<String, SoftReference<Bitmap>>();

	public static void getImage(ImageView icon, String imageUrl) {
		if (imageCache.containsKey(imageUrl)) {
			Bitmap image = imageCache.get(imageUrl).get();
			if (image != null) {
				icon.setImageBitmap(image);
				return;
			}
		}

		new LoadImageInBackground().execute(new Object[] { icon, imageUrl });
	}

	static class LoadImageInBackground extends AsyncTask<Object, Void, Bitmap> {
		ImageView mIcon = null;
		String mUrl = null;

		@Override
		protected Bitmap doInBackground(Object... params) {
			mIcon = (ImageView) params[0];
			mUrl = (String) params[1];
			Bitmap image = getImageBitmap(mUrl);
			return image;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			mIcon.setImageBitmap(result);
			imageCache.put(mUrl, new SoftReference<Bitmap>(result));
		}

	}

	// 私有方法，获取图片资源
	private static Bitmap getImageBitmap(String url) {
		Bitmap bm = null;
		try {
			URL aURL = new URL(url);
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
		} catch (IOException e) {
			Log.e("Error", e.toString());
		}
		return bm;
	}
}